package com.ctg.behavior.calc.impala.transfer.userbehavior;

import java.util.List;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.report.userbehavior.CtUSReport;
import com.ctg.behavior.calc.impala.transfer.CtFilterTransfer;
import com.ctg.behavior.common.calc.CtCalc;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUSTransfer extends CtFilterTransfer {

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtUSReport)) {
			log.warn("calcObject is not CtUSReport, class={}", calcObject.getClass());
			log.warn("calcObject: {}", JSON.toJSON(calcObject));
			log.warn("calcObject-sqlParam: {}", JSON.toJSON(sqlParam));
			return "";
		}
		CtUSReport report = (CtUSReport) calcObject;
		log.info("report={}", JSON.toJSONString(report));

		StringBuilder impalaSQL = new StringBuilder();

		// 1. SELECT部分字段
		impalaSQL.append(" SELECT device_id AS deviceId, user_id AS userId ");
		impalaSQL.append(" , event AS event ");
		impalaSQL.append(" , event_date AS eventDate ");
		impalaSQL.append(" , event_time AS eventTime ");

		List<String> properties = report.getProperties();
		for (String property : properties) {
			impalaSQL.append(" , ").append(property).append(" AS ").append(property);
		}
		// 2. 表及表关联
		impalaSQL.append(" FROM a_event_parquet_").append(report.getAppId());
		impalaSQL.append(" WHERE 1=1 ");
		// 3. deviceId 限制
		impalaSQL.append(" AND device_id = '").append(report.getDeviceId()).append("' ");
		impalaSQL.append(" AND user_id = '").append(report.getUserId()).append("' ");
		// 4. 统计事件
		List<String> events = report.getEvents();
		if (!events.isEmpty()) {
			impalaSQL.append(" AND ( ");
			for (int index = 0; index < events.size(); index++) {
				if (index > 0) {
					impalaSQL.append(" OR ");
				}
				impalaSQL.append(" event = '").append(events.get(index)).append("' ");
			}
			impalaSQL.append(" ) ");
		}
		// 5. 时间戳(按loadType：hour/detail 参数划分的时间戳)
		impalaSQL.append(" AND event_time >= '").append(report.getCalcDate().getFromDate().getTime()).append("' ");
		impalaSQL.append(" AND event_time <= '").append(report.getCalcDate().getToDate().getTime()).append("' ");
		// 6. ORDER BY (按事件时间： 升序-true / 降序-false, sequenceAsc)
		if (report.getSequenceAsc()) {
			impalaSQL.append(" ORDER BY event_time ASC ");
		} else {
			impalaSQL.append(" ORDER BY event_time DESC ");
		}

		return impalaSQL.toString();
	}

}
